package com.dayuan.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dayuan.bean.Goods;
import com.dayuan.bean.Order;
import com.dayuan.bean.OrderInfo;
import com.dayuan.bean.Store;
import com.dayuan.constant.ConstantCode;
import com.dayuan.dao.GoodsMapper;
import com.dayuan.dao.OrderInfoMapper;
import com.dayuan.dao.OrderMapper;
import com.dayuan.dao.StoreMapper;
import com.dayuan.exception.StoreException;
import com.dayuan.utils.DateUtils;

@Service
public class OrderService {
	private static Logger logger = LoggerFactory.getLogger(OrderService.class);

	@Resource
	private OrderMapper orderMapper;

	@Resource
	private OrderInfoMapper orderInfoMapper;

	@Resource
	private StoreMapper storeMapper;

	@Resource
	private GoodsMapper goodsMapper;

	public List<Order> selectOrderByStatus(Integer status, Long uid) {
		Map<String, Object> params = new HashMap<>();
		if (status != -1) {
			params.put("status", status);
		}
		params.put("uid", uid);
		return orderMapper.selectOrderByStatus(params);
	}
	


	/**
	 * 提交订单接口
	 * 
	 * @param goodsId
	 * @param buyNum
	 * @param order
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void submitOrder(Long goodsId, Integer buyNum, Order order, Long uid) throws Exception {
		Store store = storeMapper.selectByGoodId(goodsId);
		if (store == null) {
			throw new Exception("库存不足！");
		}

		// 锁库存
		store = storeMapper.selectByPrimaryKeyAndLock(store.getId());

		// 判断库存数量
		if (store.getStoreNum().intValue() < buyNum.intValue()) {
			throw new StoreException(ConstantCode.STORE_LOW);
		}

		// 更新库存
		storeMapper.updateByPrimaryKeySelective(new Store(store.getId(), (store.getStoreNum() - buyNum)));

		// 查询商品单价
		Goods goods = goodsMapper.selectGoodsById(goodsId);

		// 插入订单主表
		order.setOrderTime(DateUtils.DateToStr(new Date()));
		order.setTotalAmount(goods.getDiscountPrice() * buyNum);
		order.setUid(uid);
		orderMapper.insertOrder(order);

		// 插入订单从表
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setOrderId(order.getId());
		orderInfo.setGoodId(goodsId);
		orderInfo.setBuyNum(buyNum);
		orderInfo.setSinPrice(goods.getDiscountPrice());
		orderInfoMapper.insertSelective(orderInfo);
	}

}
